
import { CONFIG } from "../../config"; 
const WebSocket = require('ws');
 
export class WSClient {
    private wsServer: any;
    private wsUrl: string;
    constructor(ws) {
        this.wsUrl = ws;
        this.wsServer = new WebSocket(ws);
        this.wsServer.onopen = (e) => this.eventOpen(e);
        this.wsServer.onclose = (e) => this.eventClose(e);
        this.wsServer.onmessage = (e) => this.eventMessage(e);
        this.wsServer.onerror = (e) => this.eventError(e);
    }

    public sendData(data) {
        this.wsServer.send(data);//向后台发送数据 
    }
    /**
     * 链接成功后触发
     * @param e 
     */
    public eventOpen(e) {
        console.log("连接成功!");
        console.log(e);
        let data = { id: CONFIG.nodeName, versions: CONFIG.versions, wsList: CONFIG.wsArray, type: 1 };
        this.sendData(data);
    }

    /**
     * 当链接关闭的时候触发
     */
    public eventClose(e) {
        console.log("连接关闭!");
        console.log(e);
    }
    /**
     * 后台返回消息的时候触发
     * @param e 
     */
    public eventMessage(e) {
        console.log("收到消息!");
        console.log(e);
    }

    /**
     * 错误情况触发
     * @param e 
     */
    public eventError(e) {
        console.log("连接错误!");
        console.log(e);
    }


    public checkState() {
        switch (this.wsServer.readyState) {
            case WebSocket.CONNECTING://表示正在连接。
                // do something
                break;
            case WebSocket.OPEN://表示连接成功，可以通信了。

                let index = CONFIG.wsArray.indexOf(this.wsUrl);
                if (index == -1) {
                    CONFIG.wsArray.push(this.wsUrl);//如果节点不存在则添加该节点
                }
                break;
            case WebSocket.CLOSING://表示连接正在关闭。
                break;
            case WebSocket.CLOSED://表示连接已经关闭，或者打开连接失败。
                index = CONFIG.wsArray.indexOf(this.wsUrl);
                delete CONFIG.wsArray[index];//移除失效的节点 
                break;
            default:
                // this never happens
                break;
        }
    }


}


